# Util.rb
#

module KDTree
  
  #
  # SuitableRectFinder
  #
  class SuitableRectFinder
    
    def find (points)
      if not ValidPointsChecker.new.check?(points)
        Rect.new
      end
      
      Rect.new(BoundaryPoints.new.topLeft(points), BoundaryPoints.new.bottomRight(points))
    end
    
  end
  
  #
  # BoundaryPoints
  #
  class BoundaryPoints
    
    #
    # Min Point and Max Point on X axis
    #
    def topLeft (points)
      if not ValidPointsChecker.new.check?(points)
        points[0]
      end
      
      leftXPt = points[0]
      topYPt = points[0]
      
      for point in points
        if point.x < leftXPt.x
          leftXPt = point
        end
        
        if point.y > topYPt.y
          topYPt = point
        end
      end
      
      Point.new leftXPt.x, topYPt.y
    end
    
    #
    # Min Point and Max Point on Y axis
    #
    def bottomRight (points)
      if not ValidPointsChecker.new.check?(points)
        points[0]
      end
      
      bottomYPt = points[0]
      rightXPt = points[0]
      
      for point in points
        if point.y < bottomYPt.y
          bottomYPt = point
        end
        
        if point.x > rightXPt.x
          rightXPt = point
        end
      end
      
      Point.new rightXPt.x, bottomYPt.y
    end
    
  end
  
  #
  # ValidPointsChecker
  #
  class ValidPointsChecker
    
    def check? (points)
      if points.size > 1
        true
      else
        false
      end
    end
    
  end
  
end
